import config from '../config/config.js'
import moment from './plugins/moment.min.js'

function isArray(obj) {
  if (typeof obj == "object" && obj.constructor == Array) {
    return true;
  }
  return false;
}

function format() {
  ///	<summary>
  ///	字符串格式化。第一个参数是格式，第二个参数是格式化的第一个参数，第三个参数是格式化的第二个参数...
  /// var fmt = "Hello {0}!";Swao.utils.String.format(fmt, "Andrew");
  ///	</summary>
  ///	<param name="str" type="String">输入字符串</param>
  ///	<returns type="int">字符串长度(中文2个字符)</returns>

  if (arguments.length == 0)
    return null;
  var str = arguments[0];
  var re = '',
    i = 0;
  // 如果第二个参数是数组
  if (isArray(arguments[1])) {
    var array = arguments[1];
    for (; i < array.length; i++) {
      re = new RegExp('\\{' + i + '\\}', 'gm');
      str = str.replace(re, array[i]);
    }
  } else {
    for (i = 1; i < arguments.length; i++) {
      re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
      str = str.replace(re, arguments[i]);
    }
  }
  return str;
}

let cookie = {
  set: function (cookieName, data) {
    var _data = JSON.stringify({
      data: data
    });
    wx.setStorageSync(cookieName, _data)
  },
  get(cookieName) {
    var _data = wx.getStorageSync(cookieName);
    if (_data) {
      return JSON.parse(_data).data;
    }
    return null;
  },
  del(cookieName) {
    wx.removeStorageSync(cookieName);
  },
  delete(cookieName) {
    wx.removeStorageSync(cookieName);
  },
  remove(cookieName) {
    wx.removeStorageSync(cookieName);
  },
  clear() {
    wx.clearStorageSync();
  }
};


let user = {
  set(data) {
    var _data = JSON.stringify({
      data: data
    });
    // console.log('user.set-->>', _data);
    wx.setStorageSync(config.cookie.user, _data)
  },
  get() {
    var _data = wx.getStorageSync(config.cookie.user);
    if (_data) {
      return JSON.parse(wx.getStorageSync(config.cookie.user)).data || {};
    }
    return {};
  },
  remove() {
    wx.removeStorageSync(config.cookie.user);
  },
  getToken() {
    return this.get().token;
  },
  getMerchantId() {
    let user = this.get()
    return user.merchantId || user.merchant_id;
  },
  getMobile() {
    return this.get().mobile;
  },
  islogin() {
    return !!(this.get().token);
  },
  getUserName() {
    return this.get().name;
  },
  getRole() {
    return this.get().role;
  },
  isBigMerchant() { // 是否是大商户
    //console.log('isBigMerchant',this.get())
    //return true;
    return this.get().scaleType == 2;
  },
  isMiniMerchant() {
    return this.get().scaleType == 1;
  },
  setUIType(uiType = '1') {
    wx.setStorageSync(config.cookie.uiType, uiType)
  },
  getUIType() {
    return wx.getStorageSync(config.cookie.uiType);
  },
  isEasyUI() {
    var type = this.getUIType() + '';
    switch (type) {
      case '2':
        return false;
      default:
        return true;
    }
  },
  getUIName() {
    return this.isEasyUI() ? '简易版' : '标准版';
  }
};

function isTab(name) {
  // console.log('isTab->111',name);
  var tabList = config.tabList;
  // console.log('tabList',tabList)
  for (var i = 0, len = tabList.length; i < len; i++) {
    if (tabList[i] == name) {
      return true;
    }
  }
  return false;
}

let url = {
  getURL(_url, param) {
    if (param) {
      _url = _url + '?';
      for (var name in param) {
        let _value = param[name];
        _value = typeof _value == 'object' ? JSON.stringify(_value) : _value;
        _url = _url + name + '=' + _value + '&';
      }
      _url = _url.substring(0, _url.length - 1);
    }
    return _url;
  },
  go(rootName, param = null) {
    var fileName = 'pages';
    var _url = format('/{0}/{1}/{2}', fileName, rootName, rootName);
    // param = typeof param == 'object' ? JSON.stringify(param) : param;
    _url = this.getURL(_url, param);
    console.log('_url', _url);
    // console.log('navigateTo', _url);
    console.log('isTab--------->', isTab(rootName))
    if (isTab(rootName)) {
      this.switchTab(rootName, param);
      return false;
    }
    // console.log('111')
    wx.navigateTo({
      url: _url
    })
  },
  redirect(rootName, param = null) {
    var fileName = 'pages';
    var _url = format('/{0}/{1}/{2}', fileName, rootName, rootName);
    _url = this.getURL(_url, param);
    // console.log('redirectTo', _url);
    if (isTab(rootName)) {
      this.switchTab(rootName, param);
      return false;
    }
    wx.redirectTo({
      url: _url
    })
  },
  switchTab(rootName, param = null) {
    var fileName = 'pages';
    var _url = format('/{0}/{1}/{2}', fileName, rootName, rootName);
    _url = this.getURL(_url, param);
    // console.log('switchTab', _url);
    config.switchTabParam = param;
    wx.switchTab({
      url: _url,
      success: function (e) {
        var page = getCurrentPages().pop();
        if (page == undefined || page == null) return;
        page.onLoad();
      }
    })
  },
  back(step = 1) {
    wx.navigateBack({
      delta: step
    });
  },
  goLogin(e) {
    if (e) {
      var mobileIv = e.detail.iv
      var mobileEncryptedData = e.detail.encryptedData;
      cookie.set(config.cookie.wxAuthMobileInfo, {
        mobileIv: mobileIv,
        mobileEncryptedData: mobileEncryptedData
      });
    }
    var pages = getCurrentPages();
    pages = (pages[pages.length - 1] || {}).route.split('/')
    var routeName = pages[pages.length - 1];
    this.setLoginBack(routeName);
    this.go('login');
  },
  loginExpired() {
    var self = this;
    var pages = getCurrentPages()    //获取加载的页面
    var currentPage = pages[pages.length-1]    //获取当前页面的对象
    var url = currentPage.route    //当前页面url
    if(!url.indexOf('login')>-1){
      wx.showModal({
        title: '提示',
        content: '您的登录已过期，需要重新登录。',
        success: function (sm) {
          if (sm.confirm) {
            user.remove();
            self.goLogin();
          }
        }
      });
    }
  },
  setLoginBack(page) {
    wx.setStorageSync(config.cookie.loginBack, page);
  },
  loginBack() {
    let loginBack = wx.getStorageSync(config.cookie.loginBack);
    if (loginBack) {
      this.go(loginBack);
      wx.removeStorageSync(config.cookie.loginBack);
    } else {
      this.go('terminal_list');
    }
  },
  parse(url = '', key) {
    var paramStr = url.split('?')[1];
    var result = null;
    var params, paramArr;
    if (paramStr.length > 0) {
      params = paramStr.split("&");
      if (typeof key == 'undefined') {
        result = {};
        for (var i = 0; i < params.length; i++) {
          paramArr = params[i].split("=");
          result[paramArr[0]] = paramArr[1];
        }
        if (JSON.stringify(result) == '{}') {
          result = null;
        }
      } else {
        for (var j = 0; j < params.length; j++) {
          paramArr = params[j].split("=");
          var indexKey = paramArr[0];
          if (key == indexKey) {
            result = paramArr[1];
          }
        }
      }
    }
    return result;
  },
  getBaseImgURL() {
    return config.PARAM.IMG_URL+'upload/' + user.getMerchantId() + '/';
  },
  getBaseScreenShotsURL(){
    return config.PARAM.IMG_URL+'screenshots/' + user.getMerchantId() + '/';
  },
  gen(path) {
    return this.getBaseImgURL() + path;
  }
}

let terminal = {
  set(data) {
    var _data = JSON.stringify({
      data: data
    });
    wx.setStorageSync(config.cookie.currentTerminal, _data)
  },
  get() {
    // console.log(wx.getStorageSync(config.cookie.user));
    var _data = wx.getStorageSync(config.cookie.currentTerminal);
    if (_data) {
      return JSON.parse(wx.getStorageSync(config.cookie.currentTerminal)).data || {};
    }
    return {};
  },
  ajaxGet(callbackFn, terminalId) {
    if (terminalId) {
      ajax('terminal/read', {
        id: terminalId
      }).then(function (res) {
        if (res.code == 0) {
          if (callbackFn) callbackFn(res.data);
        } else {
          if (callbackFn) callbackFn(null);
        }
      })
    } else {
      var _data = wx.getStorageSync(config.cookie.currentTerminal);
      if (_data) {
        var terminalId = (JSON.parse(wx.getStorageSync(config.cookie.currentTerminal)).data || {}).id;
        ajax('terminal/read', {
          id: terminalId
        }).then(function (res) {
          if (res.code == 0) {
            if (callbackFn) callbackFn(res.data);
          } else {
            if (callbackFn) callbackFn(null);
          }
        })
      } else {
        callbackFn(null)
      }
    }

  },
  remove() {
    wx.removeStorageSync(config.cookie.currentTerminal);
  }
}

async function ajax(api, options = {}, callbackFn) {
  let _api = api.indexOf('://') > -1 ? api : (config.PARAM.API_BASE_URL + api);
  let token = user.getToken();
  options = {
    url: _api,
    method: options.method || 'POST',
    header: {
      'Accept': 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
    },
    unToken: options.unToken === true,
    dataType: options.dataType || 'json',
    networkTimeout: {
      "request": options.timeout || 120000
    },
    data: {
      ...options
    }
  };
  if (!token) {
    if (!options.unToken) {
      url.goLogin();
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          return {};
        }, 0);
      })
    }
  } else {
    options.header.token = token;
  }
  return new Promise((resolve, reject) => {
    options.success = function (res) {
      const {
        data,
        ...meta
      } = res.data;
      res.data = data;
      var resolveData = {
        ...res,
        ...meta
      };
      if (resolveData.code == 400) {
        url.loginExpired();
      }
      resolve({
        ...res,
        ...meta
      });
    };
    options.fail = function (res) {
      console.log('ajax fail',res)
      resolve(res);
    };
    wx.request(options);
  })
}

// 获取阿里上传的token
function getAliToken(callbackFn, api = config.apiName.aliUploadToken) {
  let getToken = function () {
    ajax(api, {
      policy: {
        "expiration": moment().add('hours', 1).format("YYYY-MM-DDTHH:mm:ss.000") + 'Z', //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
        "conditions": [
          ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
        ]
      }
    }).then((res) => {
      if (res.code == 0) {
        config._ali_uptoken = {
          accessKeyId: res.data.accessKeyId,
          policyBase64: res.data.policyBase64,
          signature: res.data.signature,
          time: new Date().getTime()
        };
        callbackFn(config._ali_uptoken);
      } else {
        wx.showToast({
          title: '获取阿里上传的签名失败',
          icon: 'none',
        });
      }
    });
  };
  if (!!config._ali_uptoken && config._ali_uptoken.signature) {
    // 签名时间超过半个小时，则重新请求
    if (new Date().getTime() - config._ali_uptoken.time > (30 * 60 * 1000)) {
      getToken();
    } else {
      callbackFn(config._ali_uptoken);
    }
  } else {
    getToken();
  }
}

function getFileType(type) {
  if (type.indexOf('image') > -1) {
    return 'image';
  } else if (type.indexOf('video') > -1) {
    return 'video';
  } else if (type.indexOf('zip') > -1) {
    return 'app';
  } else if (type.indexOf('mp3') > -1) {
    return 'audio';
  } else {
    return '';
  }
}

function createResource(options, callbackFn) {
  // console.log('createResource  1')
  ajax('storage/parse', {
    filePath: options.url,
    fileType: getFileType(options.type)
  }).then(function (parseRes) {
    // console.log('createResource  2', parseRes)
    if (parseRes.code == 0) {
      ajax('resource/create', {
        name: (options.name.indexOf('/') > -1 ? options.name.split('/')[options.name.split('/').length - 1] : options.name),
        data: options.url || options.data,
        type: getFileType(options.type),
        size: options.size,
        width: parseRes.data.width || 0,
        height: parseRes.data.height || 0,
        quality: options.videoType || options.quality || 3
      }).then(function (crtRes) {
        // console.log('createResource  3', crtRes)
        if (crtRes.code == 0) {
          callbackFn(crtRes);
        }
      });
    }
  });
}

function GUID() {
  this.date = new Date();
  /* 判断是否初始化过，如果初始化过以下代码，则以下代码将不再执行，实际中只执行一次 */
  if (typeof this.newGUID != 'function') {

    /* 生成GUID码 */
    GUID.prototype.newGUID = function () {
      this.date = new Date();
      var guidStr = '';
      var sexadecimalDate = this.hexadecimal(this.getGUIDDate(), 16);
      var sexadecimalTime = this.hexadecimal(this.getGUIDTime(), 16);
      for (var i = 0; i < 9; i++) {
        guidStr += Math.floor(Math.random() * 16).toString(16);
      }
      guidStr += sexadecimalDate;
      guidStr += sexadecimalTime;
      while (guidStr.length < 32) {
        guidStr += Math.floor(Math.random() * 16).toString(16);
      }
      return this.formatGUID(guidStr);
    };

    /*
     * 功能：获取当前日期的GUID格式，即8位数的日期：19700101
     * 返回值：返回GUID日期格式的字条串
     */
    GUID.prototype.getGUIDDate = function () {
      return this.date.getFullYear() + this.addZero(this.date.getMonth() + 1) + this.addZero(this.date.getDay());
    };

    /*
     * 功能：获取当前时间的GUID格式，即8位数的时间，包括毫秒，毫秒为2位数：12300933
     * 返回值：返回GUID日期格式的字条串
     */
    GUID.prototype.getGUIDTime = function () {
      return this.addZero(this.date.getHours()) + this.addZero(this.date.getMinutes()) + this.addZero(this.date.getSeconds()) + this.addZero(parseInt(this.date.getMilliseconds() / 10));
    };

    /*
     * 功能: 为一位数的正整数前面添加0，如果是可以转成非NaN数字的字符串也可以实现
     * 参数: 参数表示准备再前面添加0的数字或可以转换成数字的字符串
     * 返回值: 如果符合条件，返回添加0后的字条串类型，否则返回自身的字符串
     */
    GUID.prototype.addZero = function (num) {
      if (Number(num).toString() != 'NaN' && num >= 0 && num < 10) {
        return '0' + Math.floor(num);
      } else {
        return num.toString();
      }
    };

    /*
     * 功能：将y进制的数值，转换为x进制的数值
     * 参数：第1个参数表示欲转换的数值；第2个参数表示欲转换的进制；第3个参数可选，表示当前的进制数，如不写则为10
     * 返回值：返回转换后的字符串
     */
    GUID.prototype.hexadecimal = function (num, x, y) {
      if (y != undefined) {
        return parseInt(num.toString(), y).toString(x);
      } else {
        return parseInt(num.toString()).toString(x);
      }
    };

    /*
     * 功能：格式化32位的字符串为GUID模式的字符串
     * 参数：第1个参数表示32位的字符串
     * 返回值：标准GUID格式的字符串
     */
    GUID.prototype.formatGUID = function (guidStr) {
      var str1 = guidStr.slice(0, 8) + '-',
        str2 = guidStr.slice(8, 12) + '-',
        str3 = guidStr.slice(12, 16) + '-',
        str4 = guidStr.slice(16, 20) + '-',
        str5 = guidStr.slice(20);
      return str1 + str2 + str3 + str4 + str5;
    };
  }
}

function previewImage(event) {
  var imgs = [];
  var urls = [];
  var _url, trg, src;
  if (event.useImg) {
    src = event.previewImage;
    imgs = [];
  } else {
    trg = getTargetData(event);
    imgs = trg.imgs || [];
    src = trg.src || ''; //获取data-src
  }
  imgs.forEach(function (d) {
    _url = d.url || d;
    _url = _url.indexOf('://') > -1 ? _url : (config.PARAM.FILE_BASE_URL + _url);
    urls.push(_url);
  });
  src = src.indexOf('://') > -1 ? src : (config.PARAM.FILE_BASE_URL + src);
  if (urls.length == 0 && src) {
    urls.push(src);
  }
  // console.log('before preview', src, urls)
  //图片预览
  wx.previewImage({
    current: src, // 当前显示图片的http链接
    urls: urls // 需要预览的图片http链接列表
  })
}

function clone(data) {
  return typeof data == 'object' ? JSON.parse(JSON.stringify(data)) : data;
}

function log() {
  console.log(...arguments)
}

function getTargetData(targetObj = {}, name) {
  if (name) {
    return ((targetObj.currentTarget || {}).dataset || {})[name];
  } else {
    return ((targetObj.currentTarget || {}).dataset || {});
  }

}

function getScreenDirection(shoWDirection = 1, currentAngle = 0) {
  // console.log('getScreenDirection', shoWDirection, currentAngle)
  var result = 1; // 默认横屏 1是横屏，2是竖屏
  if (shoWDirection == 1) {
    if (currentAngle == 0 || currentAngle == 180) {
      result = 1;
    } else {
      result = 2;
    }
  } else if (shoWDirection == 2) {
    if (currentAngle == 0 || currentAngle == 180) {
      result = 2;
    } else {
      result = 1;
    }
  }
  return result;
}

function getPageShotsParam() {
  return {
    quickUrl: config.PARAM.BASE_URL + '?quickLogin={0}#/login',
    url: config.PARAM.BASE_URL + '#/customfull/program_create/id%3D{0}%26type%3Dedit',
    domId: 'layout_inner'
  };
}

function getComponentName(type) {
  switch (type) {
    case 'image':
    case 'media':
      return '图片';
    case 'text':
      return '文字';
    default:
      return '';
  }
}

function isVisitGuide() {
  return cookie.get(config.cookie.visitGuide) === true;
}

function setVisitGuide() {
  cookie.set(config.cookie.visitGuide, true);
}

function getTerminalProgram(terminalId, callbackFn) {
  ajax('terminal/channel-period', {
    terminalId: terminalId
  }).then(function (res) {
    if (res.code == 0) {
      if (res.data.channelPeriod.length > 0) {
        var prmId = res.data.channelPeriod[0].channelSchedulePeriodInfos[0].channelPlayProgramGroupInfos[0].programId;
        if (callbackFn) callbackFn(prmId);
        // ajax('program/v2/read', {
        //   id: prmId
        // }).then(function (prmDataRes) {
        //   if(prmDataRes.code == 0){
        //     var newPrmData = JSON.parse(JSON.stringify(prmDataRes.data));
        //     if(callbackFn)callbackFn(newPrmData);
        //   }else{
        //     if(callbackFn)callbackFn(null);
        //   }
        // })
      } else {
        //self.createScheduleAndProgram();
        if (callbackFn) callbackFn(null);
      }
    } else {
      if (callbackFn) callbackFn(null);
    }
  })
}

function clearProgram(terminalId, callbackFn, resetSide) {
  getTerminalProgram(terminalId, function (newPrmData) {
    if (newPrmData) {
      newPrmData.programComponent = [];
      newPrmData.pageShots = getPageShotsParam();
      if (resetSide) {
        terminal.ajaxGet(function (res) {
          var direction = getScreenDirection(res.screenPoint, res.screenAngle);
          var longSide = res.posX > res.posY ? res.posX : res.posY; // 长边
          var shortSide = res.posX > res.posY ? res.posY : res.posX; // 短边
          newPrmData.canvasWidth = (direction == 1 ? longSide : shortSide);
          newPrmData.canvasHeight = (direction == 1 ? shortSide : longSide);
          ajax('program/v2/update', newPrmData).then(function (updatePrmRes) {
            if (callbackFn) callbackFn();
          })
        }, terminalId);
      } else {
        ajax('program/v2/update', newPrmData).then(function (updatePrmRes) {
          if (callbackFn) callbackFn();
        })
      }
    } else {
      callbackFn();
    }
  });
}

function cleanPublishContent(terminalId, callbackFn) {
  var removeProgram = function (programId) {
    ajax('program/delete', { id: programId }).then(res => {

    })
  }
  var removeChannel = function (channel) {
    ajax('channel/delete', { id: channel.id }).then(res => {
      if (res.code == 0) {
        (channel.channelSchedulePeriodInfos || []).forEach(sItem => {
          (sItem.channelPlayProgramGroupInfos || []).forEach(program => {
            removeProgram(program.programId);
          })
        })
      }
    });
  }
  var stopTerminalChannel = function (channel) {
    ajax('channelPublish/terminalChannelSwitch', {
      terminalChannel: [{
        channelId: channel.id,
        terminalId: terminalId
      }],
      status: 0
    }).then(function (res) {
      if (res.code == 0) {
        console.log('-------删除channel---------')
        removeChannel(channel)
      }
    })
  }
  setTimeout(function () {
    ajax('terminal/channel-period', {
      terminalId: terminalId
    }).then(function (res) {
      if (res.code == 0) {
        if (((res.data || {}).channelPeriod || []).length > 0) {
          res.data.channelPeriod.forEach(channel => {
            stopTerminalChannel(channel);
          })
        }
      }
      if (callbackFn) callbackFn();
    })
  }, 100)
}

function byteConversion(byteValue) {
  if (byteValue <= 0) return '0 KB';
  byteValue = (byteValue + '').toLowerCase();
  if (byteValue.indexOf('kb') > -1 || byteValue.indexOf('mb') > -1 || byteValue.indexOf('gb') > -1) return byteValue;
  byteValue = parseInt(byteValue);
  if (byteValue / 1024 / 1024 < 1) {
    return parseFloat((byteValue / 1024).toFixed(2)) + ' KB';
  } else if (byteValue / 1024 / 1024 / 1024 < 1) {
    return parseFloat((byteValue / 1024 / 1024).toFixed(2)) + ' MB';
  } else {
    return parseFloat((byteValue / 1024 / 1024 / 1024).toFixed(2)) + ' GB';
  }
}
function fe_guid(name = '') {
  return name + (new GUID().newGUID());
}

function clearTerminalChoose() {
  cookie.remove(config.cookie.terminalChoose);
}

function setUntreatedAlarmEvent(callbackFn) {
  ajax('alarmEvent/untreated/search').then(res => {
    if(res.code == 0){
      let data = res.data || 0;
      if(data>0){
        wx.setTabBarBadge({
          index: 1,
          text: data+'',
          complete: function (r) {
            console.log('complete', r)
          }
        })
      }else{
        wx.hideTabBarRedDot({index:1});
      }
    }else{
      wx.hideTabBarRedDot({index:1});
    }
    if (callbackFn) callbackFn(res.data || 0);
  })
}

function isSameDay(first,second){
  return moment(first, 'YYYY-MM-DD').isSame(moment(second, 'YYYY-MM-DD'), 'day');
}

module.exports = {
  format: format,
  config: config,
  user: user,
  ajax: ajax,
  url: url,
  isArray: isArray,
  moment: moment,
  getAliToken: getAliToken,
  createResource: createResource,
  GUID: GUID,
  fe_guid: fe_guid,
  previewImage: previewImage,
  clone: clone,
  log: log,
  getTargetData: getTargetData,
  getScreenDirection: getScreenDirection,
  getPageShotsParam: getPageShotsParam,
  cookie: cookie,
  terminal: terminal,
  getComponentName: getComponentName,
  isVisitGuide: isVisitGuide,
  setVisitGuide: setVisitGuide,
  clearProgram: clearProgram,
  cleanPublishContent: cleanPublishContent,
  getTerminalProgram: getTerminalProgram,
  byteConversion: byteConversion,
  clearTerminalChoose: clearTerminalChoose,
  setUntreatedAlarmEvent: setUntreatedAlarmEvent,
  isSameDay:isSameDay
}